import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { compare } from 'bcryptjs';

// 登录尝试记录
const loginAttempts = new Map();

// 密码验证函数
const validatePassword = (password) => {
  // 密码至少8位，包含大小写字母和数字
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
  return passwordRegex.test(password);
};

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: "用户名", type: "text" },
        password: { label: "密码", type: "password" }
      },
      async authorize(credentials) {
        if (!credentials?.username || !credentials?.password) {
          throw new Error('请输入用户名和密码');
        }

        // 检查登录尝试次数
        const attempts = loginAttempts.get(credentials.username) || { count: 0, timestamp: Date.now() };
        if (attempts.count >= 5) {
          const timeDiff = Date.now() - attempts.timestamp;
          if (timeDiff < 15 * 60 * 1000) { // 15分钟冷却时间
            throw new Error('登录尝试次数过多，请15分钟后再试');
          }
          // 重置尝试次数
          attempts.count = 0;
        }

        // 验证用户名和密码
        if (credentials.username === process.env.ADMIN_USERNAME && 
            credentials.password === process.env.ADMIN_PASSWORD) {
          // 登录成功，重置尝试次数
          loginAttempts.delete(credentials.username);
          
          return {
            id: 1,
            name: 'Admin',
            email: 'admin@example.com',
            isAdmin: true,
          };
        }

        // 登录失败，增加尝试次数
        attempts.count++;
        attempts.timestamp = Date.now();
        loginAttempts.set(credentials.username, attempts);
        
        throw new Error('用户名或密码错误');
      }
    })
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.isAdmin = user.isAdmin;
      }
      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.isAdmin = token.isAdmin;
      }
      return session;
    },
    async redirect({ url, baseUrl }) {
      // 如果是相对路径，使用 baseUrl
      if (url.startsWith('/')) {
        return `${baseUrl}${url}`;
      }
      // 如果是外部 URL，检查是否允许
      if (url.startsWith(baseUrl)) {
        return url;
      }
      // 默认返回首页
      return baseUrl;
    }
  },
  pages: {
    signIn: '/auth/signin',
    signOut: '/auth/signout',
  },
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
    updateAge: 24 * 60 * 60, // 24 hours
  },
  cookies: {
    sessionToken: {
      name: `next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV === 'production',
        domain: process.env.NODE_ENV === 'production' ? undefined : undefined // 正式环境需要配置为实际域名，或让浏览器自动处理
      }
    }
  },
  secret: process.env.NEXTAUTH_SECRET,
  useSecureCookies: process.env.NODE_ENV === 'production',
  debug: process.env.NEXTAUTH_DEBUG === 'true',
  events: {
    async signOut({ session, token }) {
      // 清除登录尝试记录
      if (session?.user?.name) {
        loginAttempts.delete(session.user.name);
      }
    }
  }
};

export default NextAuth(authOptions); 